package com.galen.wxRead;

import okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

public class ProxyTest {
    // 代理服务器
    final static String proxyHost = "118.121.199.7";
    final static Integer proxyPort = 3829;

    // 代理隧道验证信息
    // 用户名和密码可到隧道代理订单页面获取：https://proxy.horocn.com/user-tunnel-orders
    // 其中，订单号为用户名
    final static String proxyUser = "s764218414";
    final static String proxyPass = "s764218414";

    static OkHttpClient client = null;

    static {

        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
        Authenticator proxyAuthenticator = new Authenticator() {
            public Request authenticate(Route route, Response response) {
                String credential = Credentials.basic(proxyUser, proxyPass);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)
                        .build();
            }
        };

        client = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50, TimeUnit.SECONDS)
                .proxy(proxy)
                .proxyAuthenticator(proxyAuthenticator)
                .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                .build();
    }

    public static Response doGet() throws IOException {
        // 要访问的目标页面
        String targetUrl = "https://www.baidu.com/";
        Request request = new Request.Builder()
                .url(targetUrl)
                .build();
        System.out.println(client.proxy().address());
        return client.newCall(request).execute();
    }

    public static void main(String[] args) throws IOException {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        Response response1 = doGet();
        System.out.println("GET请求返回结果：");
        assert response1.body() != null;
        System.out.println(response1.body().string());
    }
}